<template>
	<view :class="['v-checkbox-group', vertical ? 'vertical' : 'horizontal']" :style="groupStyle" role="checkboxgroup">
		<slot />
	</view>
</template>

<script lang="ts" setup>
import { provide, computed, ref, watch } from 'vue';

/**
 * v-checkbox-group 复选按钮组
 * value	双向绑定
 * vertical	布局方向		默认值:false		可选值:true竖		false:行
 * disabled	是否禁用		默认值:false		可选值:false不禁用	true禁用
 * indeterminate	是否开启全选/半选功能	默认值:false			可选值:false不开启	true开启
 * groupStyle	自定义样式
 * 相关事件:change
 */
const props = defineProps({
	value: {
		type: Array as () => Array<string | number | object>,
		default: () => []
	},
	vertical: {
		type: Boolean,
		default: false
	},
	disabled: {
		type: Boolean,
		default: false
	},
	indeterminate: {
		type: Boolean,
		default: false
	},
	groupStyle: {
		type: Object,
		default: () => ({})
	}
});

const emit = defineEmits(['update:value', 'change']);

const checkedValues = ref([...props.value]);

provide('checkboxGroup', {
	name: 'vCheckboxGroup',
	checkedValues,
	disabled: computed(() => props.disabled),
	indeterminate: computed(() => props.indeterminate)
});

watch(
	() => props.value,
	(newVal) => {
		checkedValues.value = [...newVal];
	}
);

const updateValues = (newValues: any[]) => {
	checkedValues.value = newValues;
	emit('update:value', newValues);
	emit('change', newValues);
};

defineExpose({
	updateValues
});
</script>

<style lang="scss">
.v-checkbox-group {
	&.horizontal {
		display: flex;
		flex-wrap: wrap;

		.v-checkbox {
			margin-right: 32rpx;

			&:last-child {
				margin-right: 0;
			}
		}
	}

	&.vertical {
		.v-checkbox {
			margin-bottom: 24rpx;

			&:last-child {
				margin-bottom: 0;
			}
		}
	}
}
</style>
